package com.glsc.ngateway.opmanage.utils.report;

import com.glsc.ngateway.opmanage.exception.PlatformException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.CollectionUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 报表导出工具类
 *
 * @author xuchang
 */
@Slf4j
public class ReportFileUtil {

    /**
     * 导出报表，返回字节流
     */
    public static <T> byte[] export(T data, ReportFileConfigEnum config) throws IOException {
        List<List<String>> datas = config.export(data);
        // 创建工作簿对象
        Workbook workbook = new XSSFWorkbook();
        // 创建工作表对象
        Sheet sheet = workbook.createSheet("Sheet1");
        //写入表头
        Row row = sheet.createRow(config.getBeginRow());
        Cell cell = null;
        List<String> titles = config.getTitle();
        for (int i = 0; i < titles.size(); i++) {
            cell = row.createCell(config.getBeginCol() + i);
            cell.setCellValue(titles.get(i));
        }
        // 创建行和单元格对象
        if (!CollectionUtils.isEmpty(datas)) {
            for (int r = 0; r < datas.size(); r++) {
                row = sheet.createRow(config.getBeginRow() + 1 + r);
                for (int c = 0; c < datas.get(r).size(); c++) {
                    cell = row.createCell(config.getBeginCol() + c);
                    // 写入数据
                    cell.setCellValue(datas.get(r).get(c));
                }
            }
        }
        // 导出Excel文件
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        workbook.close();
        return outputStream.toByteArray();
    }

    /**
     * 读取上传的excel表格
     */
    public static <T> void readSingleExcel(ReportUploadContext<T, String> context) throws IOException {
        if(Objects.isNull(context.getFile())){
            throw PlatformException.error("未找到文件", false, false);
        }
        //读取数据
        List<T> readRes = context.getConfig().readImport(context.getFile());
        if (CollectionUtils.isEmpty(readRes)) {
            throw PlatformException.error("未读取到任何数据", false, false);
        }
        context.setReadRes(readRes);
        //检查数据
        context.getReadRes().forEach(d -> {
            if(Objects.nonNull(context.getCheck())) {
                try {
                    context.getCheck().accept(d);
                } catch (PlatformException ex) {
                    context.setCheckPass(false);
                    context.getCheckRes().add(ex.getMsg());
                }
            }
        });
        context.setCheckRes(context.getCheckRes().stream().distinct().collect(Collectors.toList()));
    }
}
